#include "stdafx.h"

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "pdfwrapper.hpp"

#ifdef HPDF_DLL
void  __stdcall
#else
void
#endif

error_handler (HPDF_STATUS   error_no,
                        HPDF_STATUS   detail_no,
                        void    *user_data)
{
    fprintf (stderr, "ERROR: error_no=%04X, detail_no=%u\n", (HPDF_UINT)error_no,
                (HPDF_UINT)detail_no);
/*    longjmp(env, 1);*/
}


HPDF_Doc pdfwrapper::pdf;
HPDF_Font pdfwrapper::font;
HPDF_Page pdfwrapper::page;

pdfwrapper::pdfwrapper(const char* _fontname, float _fsize): 
	fsize(_fsize)//, fontname(_fontname)
{  

   init(_fontname);
   }


bool pdfwrapper::init(const char* _fontname)
{

 if((pdf = HPDF_New (error_handler, NULL)))
  {
  	/* set compression mode */
  	HPDF_SetCompressionMode (pdf, HPDF_COMP_ALL);

  	/* create default-font */
  	font = HPDF_GetFont (pdf, fontname.c_str(), NULL);
   }
   else
   {
	fprintf(stderr, "cannot create pdf object\n");
    return false;

   }

  return true;
}



void pdfwrapper::write(const char* _filename, const char* _str, bool _one_per_page, 
const char* _fontname, float _fsize)
{
float textwidth;

unsigned short idx(0), stringsize(strlen(_str));
    char str[] = {' ', '\0'};

if(stringsize && init(_fontname))
{

    do 
    {
    	/* add a new page object. */
    	page = HPDF_AddPage (pdf);

    	/* print the page (with positioning center). */
    	HPDF_Page_SetFontAndSize (page, font, fsize);

    	textwidth = HPDF_Page_TextWidth (page, _one_per_page? str: _str);

HPDF_Page_BeginText (page);


     HPDF_REAL xpos = (HPDF_Page_GetWidth(page) - textwidth) / 2;
			HPDF_REAL ypos = (HPDF_Page_GetHeight (page)-_fsize);
			const char *text = _one_per_page? str : _str;

HPDF_Page_TextOut (page, xpos, ypos, text);

HPDF_Page_EndText (page);

if(!_one_per_page) break;
	str[0] = _str[idx++];

     } while (idx <= stringsize);

    /* save the document to a file */
      HPDF_SaveToFile (pdf, _filename);

    HPDF_Free(pdf);
}
}

pdfwrapper::~pdfwrapper()
{
    /* clean up */
    HPDF_Free (pdf);
}

/*
int main (int argc, char **argv)

{
    const char *text = "12345678";
    char fname[256];

    strcpy (fname, argv[0]);
    strcat (fname, ".pdf");
    pdfwrapper pdfdoc;

    pdfdoc.write(fname, text, false);

   return 0;
}
*/
